<template>
  <el-popover trigger="click">
    <el-checkbox-group v-model="checkboxValue" @change="handleCheckedCitiesChange">
      <div v-for="item in checkboxData" :key="item.name">
        <el-checkbox :label="item.name" :checked="item.default">{{item.alias}}</el-checkbox>
      </div>
    </el-checkbox-group>
    <el-button size="small" type="primary" slot="reference" class="filterCloumn">全部<i class="el-icon-caret-bottom"></i></el-button>
  </el-popover>
</template>

<script>
  export default {
    name: 'JTTableColumnFilter',
    data() {
      return {
        checkboxData: this.headerData,
        checkboxValue: [],
        jtTableKey: this.tableKey,
        jtFilterColumn: this.filterColumn,
        tableHeaderOption: [],
      };
    },
    props: {
      // 表格编号
      tableKey: {
        type: Number,
        required: true,
      },
      tableName: {
        type: String,
        required: false,
      },
      // 表格 header 内可以显示的列
      headerData: {
        type: Array,
        required: true
      },
      // 表格 body 内可以显示的列
      filterColumn: {
        type: Array,
        required: true,
      }
    },
    watch: {
      checkboxValue(valArr) {

      }
    },
    methods: {
      handleCheckedCitiesChange() {
        let valArr = this.checkboxValue
        this.jtFilterColumn = this.tableHeaderOption.filter(i => valArr.indexOf(i) >= 0);


        this.jtTableKey = this.jtTableKey + 1;
        this.$emit('update:tableKey', this.jtTableKey);
        this.$emit('update:filterColumn', this.jtFilterColumn);
        this.checkboxData.forEach(e => {
          if (valArr.indexOf(e.name) >= 0) {
            e.default = true;
          } else {
            e.default = false;
          }
        });
        debugger;
        if (this.tableName) {
          localStorage.setItem("__table_filter_" + this.tableName, JSON.stringify(this.checkboxData));
        }
      }
    },
    mounted() {
      for (var value of this.checkboxData) {
        this.tableHeaderOption.push(value.name);
      }

      let headCache = localStorage.getItem("__table_filter_" + this.tableName);
      let cv = [];

      if (headCache) {
        this.checkboxData = JSON.parse(headCache);

        this.checkboxData.forEach(e => {
          if (e.default) {
            cv.push(e.name);
          }
        })
      }
      if (!cv || cv.length == 0) {
        cv = this.checkboxValue;
      }

      let valArr = cv;
      this.checkboxValue = cv;
      this.jtFilterColumn = this.tableHeaderOption.filter(i => valArr.indexOf(i) >= 0);
      this.jtTableKey = this.jtTableKey + 1;
      this.$emit('update:tableKey', this.jtTableKey);
      this.$emit('update:filterColumn', this.jtFilterColumn);
    }
  }
</script>

<style scoped>
  .el-checkbox+.el-checkbox {
    margin-left: 0px !important;
  }

  .filterCloumn {
    margin-right: 10px;
  }

  .filterCloumn i {
    padding-left: 5px;
  }
</style>
